# -*- coding: utf-8 -*-
#
# Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
# Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://opensource.org/licenses/MIT
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# Generated by Django 1.11.5 on 2018-10-10 06:32
from __future__ import unicode_literals

import json

from django.db import migrations
from django.conf import settings


def add_platform_repository(apps, schema_editor):
    """ 设置平台repo，它必须在所有用户repo添加前存在
    平台的repo用于存放charmusem仓库的chart，每次用户添加项目repo的时候， 从平台的chart中拿到chartmusem给项目部署一个repo实例
    """
    if not settings.HELM_HAS_ABILITY_SUPPLY_CHART_REPO_SERVICE:
        return

    platform_repo = settings.PLATFORM_REPO_INFO
    Repository = apps.get_model('helm', 'Repository')

    # it's seems that the migration run twice on the same database when run test with two database in settings. amazing
    if Repository.objects.filter(name=platform_repo["name"], project_id=settings.DEFAULT_MANAGE_CLUSTER["project_id"]).count():
        return

    repo = Repository.objects.create(
        url=platform_repo["url"],
        name=platform_repo["name"],
        provider=platform_repo["provider"],
        project_id=settings.DEFAULT_MANAGE_CLUSTER["project_id"],
    )

    RepositoryAuth = apps.get_model('helm', 'RepositoryAuth')
    RepositoryAuth.objects.create(
        type="BASIC",
        credentials={
            "username": "bk_paas",
            "password": "Ieg#jUJRcw3pZ5UI",
        },
        repo=repo,
        role="readonly",
    )

    # Chart = apps.get_model('helm', 'Chart')
    from backend.bcs_k8s.helm.tasks import sync_helm_repo
    sync_helm_repo(repo.id)



class Migration(migrations.Migration):

    dependencies = [
        ('helm', '0001_initial'),
    ]

    operations = [
         migrations.RunPython(add_platform_repository),
    ]
